package com.gulimall.product.web;

import com.gulimall.product.entity.CategoryEntity;
import com.gulimall.product.service.CategoryService;
import com.gulimall.product.vo.Catalog2VO;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Ren(任佳宝)
 * @Description: IndexController
 * @Date: 2025/1/19 下午7:12
 * @Version: 1.0
 */
@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redissonClient;

    @GetMapping({"/", "index.html"})
    public String indexPage(Model model) {

        List<CategoryEntity> categoryEntities = categoryService.getLevelCategory();

        model.addAttribute("categorys", categoryEntities);

        return "index";
    }

    // index/catalog.json
    @GetMapping("/index/catalog.json")
    @ResponseBody
    public Map<String, List<Catalog2VO>> getCatalogJson() {

        Map<String, List<Catalog2VO>> map = categoryService.getCatalogJson();
        return map;
    }


    /**
     * 测试redisson实现分布式锁
     */
    @ResponseBody
    @GetMapping("/testRedisson")
    public String test() {
        // 1.获取锁
        RLock lock = redissonClient.getLock("redisson_lock");

        // 2.加锁
        // 1）锁自动续期+30S，业务超长情况下（看门狗）
        // 2）如果线程宕机，看门狗不会自动续期，锁会自动过期
        // 3）unlock使用lua脚本释放锁，不会出现误删锁
        lock.lock(10, TimeUnit.SECONDS);

        try {
            // 加锁成功，执行业务
            System.out.println("加锁成功，执行业务..." + Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (Exception e) {

        } finally {
            // 3.解锁
            System.out.println("解锁..." + Thread.currentThread().getId());
            lock.unlock();
        }
        return "testRedisson";
    }

    /**
     * 测试redisson实现分布式锁
     */
    @ResponseBody
    @GetMapping("/testRedisson2")
    public String test2() {
        // 1.获取锁
        RReadWriteLock lock = redissonClient.getReadWriteLock("redisson_lock");

        // 2.加锁
        // 1）锁自动续期+30S，业务超长情况下（看门狗）
        // 2）如果线程宕机，看门狗不会自动续期，锁会自动过期
        // 3）unlock使用lua脚本释放锁，不会出现误删锁
        RLock readLock = lock.readLock();
        readLock.lock(10, TimeUnit.SECONDS);
        try {
            // 加锁成功，执行业务
            System.out.println("加锁成功，执行业务..." + Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (Exception e) {

        } finally {
            // 3.解锁
            System.out.println("解锁..." + Thread.currentThread().getId());
            readLock.unlock();
        }
        return "testRedisson";
    }

}
